//
//  NewShareViewController.m
//  ShareYOU
//
//  Created by 杨亭 on 14-12-17.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "NewShareViewController.h"
#import "DetailsShareViewController.h"
#import <MessageUI/MessageUI.h>
#import "WeiboSDK.h"
#import "WBHttpRequest.h"
#import "AppDelegate.h"
#define kRedirectURI    @"http://www.sina.com"
@interface NewShareViewController ()<UITextViewDelegate, WBHttpRequestDelegate>

{
    WBSDKRelationshipButton *relationshipButton;
    WBSDKCommentButton *commentButton;
}

@property (nonatomic, retain) NSData *dataPicture;
@property (nonatomic, retain) UILabel *titleLabel;
@property (nonatomic, retain) UIButton *shareButton;
//@property (nonatomic, retain) UISwitch *textSwitch;
//@property (nonatomic, retain) UISwitch *imageSwitch;
//@property (nonatomic, retain) UISwitch *mediaSwitch;


//添加照片按钮
@property (nonatomic, retain)UIButton *photographButton;
//添加照片显示地方
@property (nonatomic, retain)UIImageView *localAddImageView;
//添加分享文字
@property (nonatomic, retain)UITextView *addtextView;
//分享按钮
//@property (nonatomic, retain)UIButton *shareButton;
//显示剩余输入字数
@property (nonatomic, retain)UILabel *surplusInputLabel;



//
//{
//    WBSDKRelationshipButton *relationshipButton;
//    WBSDKCommentButton *commentButton;
//}







@end

@implementation NewShareViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    //创建分享页面导航栏右边的推出以前分享页面的图标
    UIImage *imageRight = [UIImage imageNamed:@"shareModule_share.png"];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:imageRight style:UIBarButtonItemStylePlain target:self action:@selector(shareAction:)] autorelease];
    
//    //设计原型的imageview
//    self.localAddImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"shareModule_oldShare.png"]];
//    self.localAddImageView.backgroundColor = [UIColor redColor];
//    self.localAddImageView.frame = CGRectMake(30.f, 80.f, 160.f, 160.f);
//    self.localAddImageView.layer.masksToBounds = YES;
//    self.localAddImageView.layer.cornerRadius = 80;
//    [self.view addSubview:self.localAddImageView];
//    [_localAddImageView release];
    
    
    
    //解决输入不是从第一行显示的问题(在textview是push出得时候,会出现让出导航栏高度的位置)
    self.automaticallyAdjustsScrollViewInsets = NO;
    

    //输入分享信息
    self.addtextView = [[UITextView alloc] initWithFrame:CGRectMake(30, 80, 330, 240)];
    //指定代理
    self.addtextView.delegate = self;
    //字体颜色
    self.addtextView.textColor = [UIColor blackColor];
    //设置字体大小
    self.addtextView.font = [UIFont fontWithName:@"Arial" size:18];
    //设置背景色
    self.addtextView.backgroundColor = [UIColor whiteColor];
    //设置自定义高度
    self.addtextView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    //是否可以拖动,默认YES。关闭暂时拖着任何
    self.addtextView.scrollEnabled = YES;
    //是否可以编辑
    self.addtextView.editable = YES;
    //设置圆角边框，先给一个圆角半径的值
    self.addtextView.layer.cornerRadius = 10;
    self.addtextView.layer. masksToBounds = YES;
    //设置键盘为默认键盘,支持所有字符
    self.addtextView.keyboardType = UIKeyboardTypeDefault;
    //设置边框颜色
    self.addtextView.layer.borderWidth = 2;
    self.addtextView.layer.borderColor = [[UIColor colorWithRed:0.3 green:0.7 blue:1 alpha:1] CGColor];
    self.addtextView.tag = 100;
    [self.view addSubview:self.addtextView];
    [_addtextView release];
    
    
    
    
    //添加照片按钮
    self.photographButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.photographButton.frame = CGRectMake(30, 268, 50, 50);
    //    //设置圆形的按钮
    //    self.photographButton.layer.masksToBounds = YES;
    //    self.photographButton.layer.cornerRadius = 70;
    [self.photographButton addTarget:self action:@selector(photographButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    //按钮添加图片
    [self.photographButton setBackgroundImage:[UIImage imageNamed:@"shareModule_photoAdd.png"] forState:UIControlStateNormal];
    [self.view addSubview:self.photographButton];
    
    
    

    
//
//    //分享按钮
//    self.shareButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    self.shareButton.frame = CGRectMake(330, 320, 30, 30);
//    [self.shareButton addTarget:self action:@selector(shareButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//    //按钮添加图片
//    [self.shareButton setBackgroundImage:[UIImage imageNamed:@"shareModule_shareBtuuon.png"] forState:UIControlStateNormal];
//    [self.view addSubview:self.shareButton];
    
    //显示输入剩余字数
    self.surplusInputLabel = [[UILabel alloc] initWithFrame:CGRectMake(290, 285, 80, 20)];
    self.surplusInputLabel.text = @"140/140";
    [self.view addSubview:self.surplusInputLabel];
    
    
//    UIButton *ssoButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//    [ssoButton setTitle:NSLocalizedString(@"请求微博认证（SSO授权）", nil) forState:UIControlStateNormal];
//    [ssoButton addTarget:self action:@selector(ssoButtonPressed) forControlEvents:UIControlEventTouchUpInside];
//    ssoButton.frame = CGRectMake(20, 90, 280, 40);
//    [self.view addSubview:ssoButton];

    
    self.shareButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.shareButton.titleLabel.numberOfLines = 2;
    self.shareButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.shareButton setTitle:NSLocalizedString(@"", nil) forState:UIControlStateNormal];
    [self.shareButton setBackgroundImage:[UIImage imageNamed:@"shareModule_shareBtuuon.png"] forState:UIControlStateNormal];
    [self.shareButton addTarget:self action:@selector(shareButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    self.shareButton.frame = CGRectMake(330, 320, 30, 30);
    [self.view addSubview:self.shareButton];

//    UIButton *openAPIButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//    [openAPIButton setTitle:NSLocalizedString(@"调用OpenAPI", nil) forState:UIControlStateNormal];
//    [openAPIButton addTarget:self action:@selector(requestOpenAPI) forControlEvents:UIControlEventTouchUpInside];
//    openAPIButton.frame = CGRectMake(20, 410, 280, 40);
//    [self.view addSubview:openAPIButton];

//    AppDelegate *myDelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
//    relationshipButton = [[[WBSDKRelationshipButton alloc] initWithFrame:CGRectMake(20, 460, 140, 30) accessToken:myDelegate.wbtoken currentUser:myDelegate.wbCurrentUserID followUser:@"2002619624" completionHandler:^(WBSDKBasicButton *button, BOOL isSuccess, NSDictionary *resultDict) {
//        
//        NSString* accessToken = [resultDict objectForKey:@"access_token"];
//        if (accessToken)
//        {
//            myDelegate.wbtoken = accessToken;
//        }
//        NSString* uid = [resultDict objectForKey:@"uid"];
//        if (uid)
//        {
//            myDelegate.wbCurrentUserID = uid;
//        }
//        
//        
//    }] autorelease];
//    
//    [self.view addSubview:relationshipButton];
    
//    UILabel *textLabel = [[[UILabel alloc] initWithFrame:CGRectMake(10, 200, 80, 30)] autorelease];
//    textLabel.text = NSLocalizedString(@"文字", nil);
//    textLabel.backgroundColor = [UIColor clearColor];
//    textLabel.textAlignment = NSTextAlignmentCenter;
//    self.textSwitch = [[[UISwitch alloc] initWithFrame:CGRectMake(100, 200, 120, 30)] autorelease];
//    [self.view addSubview:textLabel];
//    [self.view addSubview:self.textSwitch];
//    
//    UILabel *imageLabel = [[[UILabel alloc] initWithFrame:CGRectMake(10, 240, 80, 30)] autorelease];
//    imageLabel.text = NSLocalizedString(@"图片", nil);
//    imageLabel.backgroundColor = [UIColor clearColor];
//    imageLabel.textAlignment = NSTextAlignmentCenter;
//    self.imageSwitch = [[[UISwitch alloc] initWithFrame:CGRectMake(100, 240, 120, 30)] autorelease];
//    [self.view addSubview:imageLabel];
//    [self.view addSubview:self.imageSwitch];
//    

    
    
    
}

//显示剩余可输入字数
- (void)textViewDidChange:(UITextView *)textView {
    NSInteger number = [textView.text length];
    if (number > 140) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经输入140个字了哦!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        textView.text = [textView.text substringToIndex:140];
        number = 140;
        [alert release];
    }
    
    self.surplusInputLabel.text = [NSString stringWithFormat:@"%ld/140",140 - number];
}




//实现触摸空白回收键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITextView *textView = (UITextView *)[self.view viewWithTag:100];
    [textView resignFirstResponder];
}



//分享按钮的实现方法
- (void)shareButtonPressed
{
    AppDelegate *myDelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
    authRequest.redirectURI = kRedirectURI;
    authRequest.scope = @"all";
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:[self messageToShare] authInfo:authRequest access_token:myDelegate.wbtoken];
    request.userInfo = @{@"ShareMessageFrom": @"NewShareViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    //    request.shouldOpenWeiboAppInstallPageIfNotInstalled = NO;
    [WeiboSDK sendRequest:request];

    
    
    
    
    
    
}

- (WBMessageObject *)messageToShare
{
    WBMessageObject *message = [WBMessageObject message];
    
    if (self.dataPicture == nil) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先选择一张图片哦!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    else
    {
//    if (self.textSwitch.on)
//    {
        message.text = NSLocalizedString(@"请输入:", nil);
//    }
    
//    if (self.imageSwitch.on)
//    {
        WBImageObject *image = [WBImageObject object];
//        image.imageData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"add" ofType:@"jpg"]];
    image.imageData = self.dataPicture;
        message.imageObject = image;
    }
    
//    if (self.mediaSwitch.on)
//    {
//        WBWebpageObject *webpage = [WBWebpageObject object];
//        webpage.objectID = @"identifier1";
//        webpage.title = NSLocalizedString(@"分享网页标题", nil);
//        webpage.description = [NSString stringWithFormat:NSLocalizedString(@"分享网页内容简介-%.0f", nil), [[NSDate date] timeIntervalSince1970]];
//        webpage.thumbnailData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"image_2" ofType:@"jpg"]];
//        webpage.webpageUrl = @"http://sina.cn?a=1";
//        message.mediaObject = webpage;
//    }
    
    return message;
}


//
//- (void)requestOpenAPI
//{
//    DetailsShareViewController* httpRequestDemoVC = [[[DetailsShareViewController alloc] initWithStyle:UITableViewStyleGrouped] autorelease];
//    
//    [self presentViewController:httpRequestDemoVC animated:YES completion:^{
//    }];
//    
//}


//- (void)ssoButtonPressed
//{
//    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
//    request.redirectURI = kRedirectURI;
//    request.scope = @"all";
//    request.userInfo = @{@"SSO_From": @"NewShareViewController",
//                         @"Other_Info_1": [NSNumber numberWithInt:123],
//                         @"Other_Info_2": @[@"obj1", @"obj2"],
//                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
//    [WeiboSDK sendRequest:request];
//}



//- (void)viewOnWillDisplay:(UIViewController *)viewController shareType:(ShareType)shareType
//
//{
//    
//    //修改分享编辑框的标题栏颜色
//    viewController.navigationController.navigationBar.barTintColor = [UIColor redColor];
//    
//    //将分享编辑框的标题栏替换为图片
//    //    UIImage *image = [UIImage imageNamed:@"iPhoneNavigationBarBG.png"];
//    //    [viewController.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
//    
//}



//添加照片的按钮实现方法
- (void)photographButtonAction:(UIButton *)photographButton
{
    //在这里呼出下方菜单按钮项
    myActionSheet = [[UIActionSheet alloc]
                     initWithTitle:nil
                     delegate:self
                     cancelButtonTitle:@"取消"
                     destructiveButtonTitle:nil
                     otherButtonTitles: @"从手机相册获取",nil];
    
    [myActionSheet showInView:self.view];
    [myActionSheet release];

}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    
    //呼出的菜单按钮点击后的响应
    if (buttonIndex == myActionSheet.cancelButtonIndex)
    {
        NSLog(@"取消");
    }
    
    //判断点击的是哪一个
    switch (buttonIndex)
    {
//        case 0:  //打开照相机拍照
//            [self takePhoto];
//            break;
//            
        case 0:  //打开本地相册
            [self LocalPhoto];
            break;
    }
}

////开始拍照
//-(void)takePhoto
//{
//    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
//    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
//    {
//        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
//        picker.delegate = self;
//        //设置拍照后的图片可被编辑
//        picker.allowsEditing = YES;
//        picker.sourceType = sourceType;
//        [picker release];
//        [self presentModalViewController:picker animated:YES];
////        [self.navigationController pushViewController:picker animated:YES];
//    }else
//    {
//        NSLog(@"模拟其中无法打开照相机,请在真机中使用");
//    }
//}

//打开本地相册
-(void)LocalPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentModalViewController:picker animated:YES];
//    [self.navigationController pushViewController:picker animated:YES];
    [picker release];
}

//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    NSData *data;

    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
                if (UIImagePNGRepresentation(image) == nil)
        {
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        else
        {
            data = UIImagePNGRepresentation(image);
        }
        
        
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
        
        //得到选择后沙盒中图片的完整路径
        filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.png"];
        
        //关闭相册界面
        [picker dismissModalViewControllerAnimated:YES];
//        [picker.navigationController popViewControllerAnimated:YES];
        
        //创建一个选择后图片的小图标放在下方
        //类似微薄选择图后的效果
        self.localAddImageView = [[UIImageView alloc] initWithFrame:CGRectMake(90, 270, 45, 45)];
        self.localAddImageView.image = image;
        
        //加在视图中
        [self.view addSubview:self.localAddImageView];
        
    }
    
    self.dataPicture = data;
}

//- (NSData *)returnData:(NSData *)data{
//    
//    return data;
//    
//}



//导航栏右边分享图标方法实现
- (void)shareAction:(UIBarButtonItem *)item
{
    
    
    
    
    
}




- (void)dealloc
{
    [_photographButton release];
    [_localAddImageView release];
    [_addtextView release];
    [_shareButton release];
    [_surplusInputLabel release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
